import { useState } from 'react';
import { Form } from '@supcon/supcon-5t-design';
import { useSetState } from 'ahooks';
import { ModalProps } from './index';

export interface UseAddEditModalType {
    context: ModalProps;
    control: {
        openModal: (info?: TableUserInfoType) => void;
    };
}

export interface ModalStateType {
    info?: TableUserInfoType;
}

export default function useAddEditModal({
    okCb,
    cancelCb,
}: {
    okCb?: (res?: TableUserInfoType) => void;
    cancelCb?: () => void;
}): UseAddEditModalType {
    const [open, setOpen] = useState<boolean>(false);
    const [modalState, setModalState] = useSetState<ModalStateType>({});
    const [form] = Form.useForm<any>(undefined);
    const onCancel = () => {
        setOpen(false);
        cancelCb && cancelCb();
    };
    const onOk = async () => {
        const res = await form.validateFields();
        const resInfo = {
            ...modalState?.info,
            id: modalState.info ? modalState.info.id : 0,
            ...res
        };
        setOpen(false);
        okCb && okCb(resInfo);
    };
    const openModal = (info?: TableUserInfoType) => {
        setOpen(true);
        if (info) {
            form.setFieldsValue({
                name: info.name,
                age: info.age,
                address: info.address
            });
        } else {
            form.setFieldsValue({
                name: '',
                age: '',
                address: ''
            });
        }
        setModalState({
            info: info
        });
    };
    return {
        context: {
            open,
            form,
            modalState,
            setModalState,
            onCancel,
            onOk,
        },
        control: {
            openModal,
        },
    };
}